package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import actions.ActionHandler;

@WebServlet("*.mvc")
public class MVCController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void mvcProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String uri = req.getRequestURI();
		String cmd = uri.substring(uri.lastIndexOf("/"));
		
		System.out.println("uri:"+uri);
		System.out.println("action :"+cmd);
		// 요청 URI에 따른 action 클래스 불러오기
		ActionHandler action = (ActionHandler)MVCControllerSetup.getActionsMap().get(cmd);
		
		// 불러온 action클래스를 실행하고 결과를 출력할 viewPage를 받음 
		String viewPage = action.execute(req,res);
		String dispatcher[] = viewPage.split("[|]");
		
		if(dispatcher[0].equals("f")){ // forward라면
			RequestDispatcher rd = req.getRequestDispatcher(dispatcher[1]);
			rd.forward(req,res);
		}else if(dispatcher[0].equals("r")){ // redirect라면
			res.sendRedirect(dispatcher[1]);
			
		}
		
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		mvcProcess(req,res);
	
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		mvcProcess(req,res);
	
	}

	
	
}
